import pandas as pd
from django.shortcuts import render, get_object_or_404, redirect
from .forms import ProductLotRelForm, ProductLotRelUploadExcelForm
from .models import ProductLotRel
from django.contrib import messages

from .mylogin_utils import my_login_admin_required


@my_login_admin_required
def create_product_lot_rel(request):
    if request.method == 'POST':
        form = ProductLotRelForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('product_lot_rel_list')  # 替换为你的重定向目标
    else:
        form = ProductLotRelForm()

    return render(request, 'mainapp/create_product_lot_rel.html', {'form': form})


@my_login_admin_required
def product_lot_rel_list(request):
    # 获取所有 ProductLotRel 数据
    products = ProductLotRel.objects.all().order_by('-id')
    return render(request, 'mainapp/product_lot_rel_list.html', {'products': products})


@my_login_admin_required
def delete_product_lot_rel(request, pk):
    product = get_object_or_404(ProductLotRel, pk=pk)
    if request.method == 'POST':
        product.delete()
    return redirect('product_lot_rel_list')


@my_login_admin_required
def upload_excel(request):
    if request.method == 'POST':
        form = ProductLotRelUploadExcelForm(request.POST, request.FILES)
        if form.is_valid():
            excel_file = request.FILES['excel_file']
            try:
                df = pd.read_excel(excel_file, engine="openpyxl")
                for _, row in df.iterrows():
                    product_type = row['ProductType']
                    lot_number = row['LotNumber']
                    # 检查数据库中是否已存在相同的 ProductType 和 LotNumber 组合
                    if not ProductLotRel.objects.filter(ProductType=product_type, LotNumber=lot_number).exists():
                        ProductLotRel.objects.create(
                            ProductType=product_type,
                            LotNumber=lot_number
                        )
                messages.success(request, '数据已成功导入')
                return redirect('product_lot_rel_list')
            except Exception as e:
                messages.error(request, f'导入过程中发生错误: {e}')
    else:
        form = ProductLotRelUploadExcelForm()
    return render(request, 'mainapp/product_lot_upload_excel.html', {'form': form})
